import React, { useEffect, useRef, useState } from 'react';
import { Vehicle, Route } from '../../types';
import { 
  MapPin, 
  Navigation, 
  Truck, 
  Package,
  AlertCircle,
  CheckCircle,
  Clock,
  Zap,
  RefreshCw
} from 'lucide-react';

// 高德地图API配置
const AMAP_CONFIG = {
  key: '53f90296b61f99d1275fd26e6cad91a3',
  version: '2.0',
  plugins: ['AMap.Driving', 'AMap.Geocoder', 'AMap.ToolBar', 'AMap.Scale']
};

interface AmapContainerProps {
  vehicles: Vehicle[];
  routes: Route[];
  onVehicleClick?: (vehicle: Vehicle) => void;
  onRouteClick?: (route: Route) => void;
  className?: string;
}

declare global {
  interface Window {
    AMap: any;
    _AMapSecurityConfig: any;
  }
}

export const AmapContainer: React.FC<AmapContainerProps> = ({
  vehicles,
  routes,
  onVehicleClick,
  onRouteClick,
  className = ''
}) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const [mapInstance, setMapInstance] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [retryCount, setRetryCount] = useState(0);

  // 动态加载高德地图API
  const loadAmapScript = (): Promise<void> => {
    return new Promise((resolve, reject) => {
      // 检查是否已经加载
      if (window.AMap) {
        resolve();
        return;
      }

      // 设置安全密钥（如果需要）
      window._AMapSecurityConfig = {
        securityJSCode: '9dee2934ce3d7f88d9056f055ad2aa9a'
      };

      const script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = `https://webapi.amap.com/maps?v=${AMAP_CONFIG.version}&key=${AMAP_CONFIG.key}&plugin=${AMAP_CONFIG.plugins.join(',')}`;
      script.async = true;

      script.onload = () => {
        console.log('高德地图API加载成功');
        resolve();
      };

      script.onerror = (error) => {
        console.error('高德地图API加载失败:', error);
        reject(new Error('高德地图API加载失败，请检查网络连接'));
      };

      document.head.appendChild(script);
    });
  };

  // 初始化地图
  const initMap = async () => {
    if (!mapContainer.current) return;

    try {
      setLoading(true);
      setError(null);

      // 加载高德地图API
      await loadAmapScript();

      // 等待一小段时间确保API完全加载
      await new Promise(resolve => setTimeout(resolve, 500));

      if (!window.AMap) {
        throw new Error('高德地图API未正确初始化');
      }

      const AMap = window.AMap;

      // 创建地图实例
      const map = new AMap.Map(mapContainer.current, {
        zoom: 10,
        center: [116.397428, 39.90923], // 北京中心点
        viewMode: '2D', // 使用2D模式，更稳定
        mapStyle: 'amap://styles/normal', // 使用标准样式
        features: ['bg', 'road', 'building', 'point'],
        showLabel: true,
        resizeEnable: true
      });

      // 等待地图加载完成
      map.on('complete', () => {
        console.log('地图初始化完成');
        
        try {
          // 添加地图控件
          const toolbar = new AMap.ToolBar({
            position: {
              top: '10px',
              right: '10px'
            }
          });
          map.addControl(toolbar);

          const scale = new AMap.Scale({
            position: {
              bottom: '10px',
              left: '10px'
            }
          });
          map.addControl(scale);

          setMapInstance(map);
          setLoading(false);
          
          // 添加车辆标记
          addVehicleMarkers(map, vehicles);
          
        } catch (controlError) {
          console.error('添加地图控件失败:', controlError);
          // 即使控件添加失败，地图仍然可用
          setMapInstance(map);
          setLoading(false);
        }
      });

      // 监听地图错误
      map.on('error', (e: any) => {
        console.error('地图错误:', e);
        setError('地图加载出现错误，请重试');
        setLoading(false);
      });

    } catch (err) {
      console.error('地图初始化失败:', err);
      setError(err instanceof Error ? err.message : '地图初始化失败');
      setLoading(false);
    }
  };

  // 添加车辆标记
  const addVehicleMarkers = (map: any, vehicles: Vehicle[]) => {
    if (!vehicles.length) return;

    const AMap = window.AMap;
    
    vehicles.forEach(vehicle => {
      const statusColors = {
        available: '#22c55e',
        in_use: '#3b82f6',
        maintenance: '#f59e0b',
        offline: '#ef4444'
      };

      const statusLabels = {
        available: '空闲',
        in_use: '使用中',
        maintenance: '维护中',
        offline: '离线'
      };

      // 创建简单的圆形标记
      const marker = new AMap.CircleMarker({
        center: [vehicle.location.lng, vehicle.location.lat],
        radius: 8,
        strokeColor: '#ffffff',
        strokeWeight: 2,
        fillColor: statusColors[vehicle.status],
        fillOpacity: 0.8,
        cursor: 'pointer'
      });

      // 创建信息窗体
      const infoWindow = new AMap.InfoWindow({
        content: `
          <div style="padding: 12px; min-width: 200px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            <div style="font-weight: bold; margin-bottom: 8px; color: #1f2937; font-size: 16px;">
              ${vehicle.plateNumber}
            </div>
            <div style="margin-bottom: 4px; color: #6b7280; font-size: 14px;">
              <strong>类型:</strong> ${vehicle.type}
            </div>
            <div style="margin-bottom: 4px; color: #6b7280; font-size: 14px;">
              <strong>载重:</strong> ${vehicle.capacity}吨
            </div>
            <div style="margin-bottom: 4px; color: #6b7280; font-size: 14px;">
              <strong>司机:</strong> ${vehicle.driverName}
            </div>
            <div style="margin-bottom: 4px; color: #6b7280; font-size: 14px;">
              <strong>状态:</strong> <span style="color: ${statusColors[vehicle.status]}; font-weight: bold;">
                ${statusLabels[vehicle.status]}
              </span>
            </div>
            <div style="color: #6b7280; font-size: 14px;">
              <strong>位置:</strong> ${vehicle.location.address}
            </div>
          </div>
        `,
        offset: new AMap.Pixel(0, -20)
      });

      // 添加点击事件
      marker.on('click', () => {
        infoWindow.open(map, marker.getCenter());
        onVehicleClick?.(vehicle);
      });

      // 添加到地图
      map.add(marker);
    });

    // 自适应显示所有标记
    if (vehicles.length > 0) {
      const bounds = new AMap.Bounds();
      vehicles.forEach(vehicle => {
        bounds.extend([vehicle.location.lng, vehicle.location.lat]);
      });
      map.setBounds(bounds, false, [50, 50, 50, 50]);
    }
  };

  // 重试加载
  const handleRetry = () => {
    if (retryCount < 3) {
      setRetryCount(prev => prev + 1);
      setError(null);
      initMap();
    }
  };

  // 初始化地图
  useEffect(() => {
    const timer = setTimeout(() => {
      initMap();
    }, 100);

    return () => {
      clearTimeout(timer);
      if (mapInstance) {
        try {
          mapInstance.destroy();
        } catch (e) {
          console.warn('地图销毁失败:', e);
        }
      }
    };
  }, []);

  // 更新车辆标记
  useEffect(() => {
    if (mapInstance && vehicles.length > 0) {
      // 清除现有标记
      mapInstance.clearMap();
      // 重新添加标记
      addVehicleMarkers(mapInstance, vehicles);
    }
  }, [mapInstance, vehicles]);

  if (loading) {
    return (
      <div className={`flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 rounded-xl ${className}`}>
        <div className="text-center">
          <div className="relative">
            <div className="animate-spin rounded-full h-16 w-16 border-4 border-blue-200 border-t-blue-600 mx-auto mb-4"></div>
            <div className="absolute inset-0 flex items-center justify-center">
              <MapPin className="w-6 h-6 text-blue-600" />
            </div>
          </div>
          <p className="text-blue-800 font-medium mb-2">正在加载地图...</p>
          <p className="text-blue-600 text-sm">请稍候，正在连接高德地图服务</p>
          {retryCount > 0 && (
            <p className="text-blue-500 text-xs mt-2">重试次数: {retryCount}/3</p>
          )}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`flex items-center justify-center bg-gradient-to-br from-red-50 to-pink-100 rounded-xl ${className}`}>
        <div className="text-center max-w-md">
          <AlertCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <p className="text-red-700 font-medium mb-2">地图加载失败</p>
          <p className="text-red-600 text-sm mb-4">{error}</p>
          <div className="space-y-2">
            {retryCount < 3 ? (
              <button 
                onClick={handleRetry}
                className="inline-flex items-center px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                重试加载 ({retryCount + 1}/3)
              </button>
            ) : (
              <div className="text-red-500 text-sm">
                <p>多次重试失败，可能的原因：</p>
                <ul className="text-left mt-2 space-y-1">
                  <li>• 网络连接问题</li>
                  <li>• API密钥配置错误</li>
                  <li>• 域名未在高德平台配置</li>
                </ul>
              </div>
            )}
            <button 
              onClick={() => window.location.reload()} 
              className="block w-full px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
            >
              刷新页面
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`relative ${className}`}>
      {/* 地图容器 */}
      <div 
        ref={mapContainer} 
        className="w-full h-full rounded-xl overflow-hidden shadow-lg bg-gray-100"
        style={{ minHeight: '500px' }}
      />
      
      {/* 地图图例 */}
      <div className="absolute top-4 left-4 bg-white rounded-lg shadow-lg p-4 max-w-xs">
        <h3 className="font-semibold text-gray-800 mb-3 flex items-center">
          <MapPin className="w-4 h-4 mr-2 text-blue-600" />
          图例说明
        </h3>
        <div className="space-y-2 text-sm">
          <div className="flex items-center space-x-2">
            <div className="w-4 h-4 bg-success-500 rounded-full border-2 border-white shadow"></div>
            <span>空闲车辆</span>
          </div>
          <div className="flex items-center space-x-2">
            <div className="w-4 h-4 bg-primary-500 rounded-full border-2 border-white shadow"></div>
            <span>使用中车辆</span>
          </div>
          <div className="flex items-center space-x-2">
            <div className="w-4 h-4 bg-warning-500 rounded-full border-2 border-white shadow"></div>
            <span>维护中车辆</span>
          </div>
          <div className="flex items-center space-x-2">
            <div className="w-4 h-4 bg-error-500 rounded-full border-2 border-white shadow"></div>
            <span>离线车辆</span>
          </div>
        </div>
      </div>

      {/* 实时统计 */}
      <div className="absolute bottom-4 right-4 bg-white rounded-lg shadow-lg p-4">
        <div className="flex items-center space-x-4 text-sm">
          <div className="flex items-center space-x-1">
            <Truck className="w-4 h-4 text-primary-600" />
            <span className="font-medium">{vehicles.length}</span>
            <span className="text-gray-600">辆车</span>
          </div>
          <div className="flex items-center space-x-1">
            <Navigation className="w-4 h-4 text-secondary-600" />
            <span className="font-medium">{routes.filter(r => r.isActive).length}</span>
            <span className="text-gray-600">条路线</span>
          </div>
          <div className="flex items-center space-x-1">
            <Zap className="w-4 h-4 text-success-600" />
            <span className="font-medium">{vehicles.filter(v => v.status === 'in_use').length}</span>
            <span className="text-gray-600">在途</span>
          </div>
        </div>
      </div>

      {/* 地图状态指示器 */}
      <div className="absolute top-4 right-4">
        <div className="flex items-center space-x-2 bg-white rounded-full px-3 py-1 shadow-lg">
          <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
          <span className="text-xs text-gray-600">地图已就绪</span>
        </div>
      </div>
    </div>
  );
};